/*
 * @Author: yangrongxin
 * @Date: 2021-08-05 09:40:41
 * @LastEditors: guoju
 * @LastEditTime: 2022-01-14 09:25:25
 */
import { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import Taro, { useRouter } from '@tarojs/taro';
import { AtProgress } from 'taro-ui';
import { View, Text, Image } from '@tarojs/components';
import { submitexam } from '@/services/exam';
import { getItemSync } from '@/utils/storage';
import { STORAGE_TYPE } from '@/const/dataDictionary';
import { CHANNEL_TYPE } from '@/pages/My/compoents/MyAssessment/dataDictionary';
import type {
  SelectData
} from '@/types/exam';
import { ProgressBar, ExamContent } from './components';
import styles from './index.module.less';

const CheckboxAnswer = () => {
  const {
    params: {
      measureTableId = '1419902806618578945',
      title = '测试测评数据',
      measureTableRecordId = '264263939947235098',
      evaluationId = '',
      // 当前是团队的时候 判断当前团队能不能看进行跳转 当前是院内的时候 直接不能进行跳转
      evaluationType,
    },
  } = useRouter<{
    measureTableId: string,
    title: string,
    measureTableRecordId: string,
    evaluationId: string
    evaluationType: string
  }>();

  const dispatch = useDispatch();
  const {
    examData: {
      questionNum, questions = [], memberView = 1
    },
    curQuestionIndex,
    submitQuestionInfoList
  } = useSelector((state: any) => state.evaluation);

  const [showProgress, setShowProgress] = useState<boolean>(false); // 展示当前的提交进度弹窗
  const [percent, setPercent] = useState<number>(10); // 存储当前的提交进度
  const [loading, setLoading] = useState<boolean>(false); // 设置当前的加载状态

  useEffect(() => {
    Taro.setNavigationBarTitle({
      title,
    });
    const {
      userInfoRespVO: { name, contactMobile },
    } = getItemSync(STORAGE_TYPE.USERINFO);
    dispatch({
      type: 'evaluation/startexam',
      payload: {
        measureTableId,
        measureTableRecordId,
        evaluationId,
        evaluationType,
        name: name || contactMobile,
      },
    });
  }, []);

  /*
   * 回到上一题进行展示
   */
  const backToPrevAnswer = (answer: SelectData) => {
    dispatch({
      type: 'evaluation/prevAnswer',
      payload: {
        answer,
      },
    });
  };

  const submitQuestionAnswer = (answer: SelectData) => {
    // 如果当前是最后一次提交了 提交之后 直接请求接口返回结果
    const isLast = curQuestionIndex + 1 === questionNum;
    dispatch({
      type: 'evaluation/addAnswer',
      payload: {
        answer,
        isLast,
        callback: (data) => {
          if (!data) return;
          
          setLoading(false);
          // 当前是团队的时候判断 memberView 当前是不是能进行跳转
          if (memberView === 1 && evaluationType !== String(CHANNEL_TYPE.THECOURT)) {
            setShowProgress(true);
          }

          const timer = setTimeout(() => {
            let newPercent = percent;
            newPercent += 1;
            setPercent(newPercent);
          }, 1000);
          const dataStr = JSON.stringify(data).replace(/null,/g, '');
          const dataSub = JSON.parse(dataStr);
          console.log('finishData', data); // 提交到后端接口的数据
          console.log('submitData', dataSub);

          submitexam(dataSub).then((res: any) => {
            setLoading(true);
            // 团队用户直接回到上个页面 判断当前是不是团队的测评 目前不展示团队的个人报告
            // 当前是院内用户的时候 同时不支持在小程序端查看对应的报告 需要到管理平台进行报告查看
            if (memberView !== 1 || evaluationType === String(CHANNEL_TYPE.THECOURT) || !res) {
              setTimeout(() => {
                Taro.navigateBack();
              }, 2000);
            } else {
              // 非团队用户展示 进行中的动画
              setPercent(100);
              clearTimeout(timer);
              setTimeout(() => {
                Taro.redirectTo({
                  url: `/pages/TestReport/index?measureTableRecordId=${res.measureTableRecordId}`,
                });
              }, 1500);
            }
          });
        },
      },
    });
  };

  return (
    <View className="hxtPublicWapper">
      {/* 题目数 已完成 */}
      <ProgressBar questionNum={questionNum} curQuestionIndex={curQuestionIndex + 1} />
      {/* 展示当前考题的内容 */}
      {
        questions.length !== 0 && (
          <ExamContent
            questions={questions[curQuestionIndex]} // 当前的题目内容
            curQuestionIndex={curQuestionIndex} // 当前题目索引
            submitQuestionInfoList={submitQuestionInfoList} // 提交答案列表
            submitQuestion={submitQuestionAnswer} // 提交答案的方法
            backToPrevAnswer={backToPrevAnswer} // 返回上一题目的参数
            evaluationType={evaluationType} // 测评类型
            isLast={curQuestionIndex + 1 === questionNum} // 当前是不是最后一题的判断
            loading={loading}
          />
        )
      }
      {/* 展示当前的考题弹窗 */}
      <View className={`${styles.progress} ${showProgress ? styles.show : styles.hide}`}>
        <View>
          <Image src="https://hxgywx.oss-cn-shenzhen.aliyuncs.com/hxt-wxminiprogram/animation_progress.gif" />
          <AtProgress percent={percent} />
          <Text>测评报告生成中</Text>
        </View>
      </View>
    </View>
  );
};

export default CheckboxAnswer;
